﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BadHabit.Factory.Controls {
    /// <summary>
    /// Interaction logic for TeamMemberHeader.xaml
    /// </summary>
    public partial class TeamMemberDetail : UserControl {

        public TeamMemberDetail() {
            InitializeComponent();
            

        }

        public bool ShowAuthenticationGroupBox { get; set; }
        public bool IsClientManagement { get; set; }
        public bool IsReadingFromMSExchange { get; set; }
            
        
        private void SetChangeImageVisibility() {

            if (MemberRow == null) {
                changeImageTextBlock.Visibility = Visibility.Collapsed;
                return;
            }

            if (MemberRow.ClientContactRole) {
                changeImageTextBlock.Visibility = Visibility.Collapsed;
                return;
            }
            if (Client.UserIsInRole(TeamRoles.FACTORY_OWNER)) {
                changeImageTextBlock.Visibility = Visibility.Visible;
                return;
            }
            
            if(MemberRow.MemberId.ToLower().Equals(Client.User.Identity.Name.ToLower())) {
                changeImageTextBlock.Visibility = Visibility.Visible;
                return;
            }

            changeImageTextBlock.Visibility = Visibility.Collapsed;

            
            
        }

        private Data.TeamDataSet.MemberRow MemberRow {
            get {
                Data.TeamDataSet.MemberRow memberRow = null;
                if (DataContext is Data.TeamDataSet.MemberRow) {
                    memberRow = (Data.TeamDataSet.MemberRow)DataContext;
                } else if (DataContext is BindingListCollectionView) {
                    memberRow = Helper.GetRowFromRowView<Data.TeamDataSet.MemberRow>(((BindingListCollectionView)DataContext).CurrentItem);
                } else {
                    memberRow = Helper.GetRowFromRowView<Data.TeamDataSet.MemberRow>(DataContext);
                }
                return memberRow;
            }
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e) {
            
            if (MemberRow == null)
                return;

            Byte[] imageBytes = GetMemberImageAsBytes();
            if (imageBytes == null)
                return;

            try {
                Client.Service.UpdateTeamMemberImage(imageBytes, MemberRow.MemberId);
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_UPDATE_TEAM_MEMBERS);
                return;
            }


            MemberRow["ImageUri"] = Client.CreateMemberImageUri(MemberRow.MemberId);

        }

        private Byte[] GetMemberImageAsBytes() {
            System.Drawing.Image image = null;
            Byte[] imageBytes = null;

            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();


            dialog.Filter = "Images|*.gif;*.jpg;*.png";

            System.Windows.Forms.DialogResult d = dialog.ShowDialog();
            if (d == System.Windows.Forms.DialogResult.Cancel)
                return null;
            try {
                image = System.Drawing.Bitmap.FromFile(dialog.FileName);
            } catch (Exception) {
                Windows.Error.ShowAlert(Properties.Resources.Member_image_is_invalid);
            }
            if (image == null)
                return null;


            
            System.Drawing.Image imageResized = AutoResize(image);
            

            try {                
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                imageResized.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                imageBytes = ms.ToArray();
            } catch (Exception) {
                Windows.Error.ShowAlert(Properties.Resources.Member_image_is_invalid);
            }

            return imageBytes;
        }


        private System.Drawing.Image AutoResize(System.Drawing.Image originalImg) {
            double resizeFactor = 1;
            double MAX_DIMENSION = 100;
            int newWidth = originalImg.Width;
            int newHeight = originalImg.Height;

            
            // if image is bigger then MAX_DIMENSION x MAX_DIMENSION
            // calculates the new dimensiom
            if(originalImg.Width > MAX_DIMENSION || originalImg.Height > MAX_DIMENSION) {

                // use the lowest dimension to calculate the resize factor
                if (originalImg.Width < originalImg.Height)
                    resizeFactor = (double) (MAX_DIMENSION / originalImg.Width);                
                else
                    resizeFactor = (double) (MAX_DIMENSION / originalImg.Height);

                newWidth = (int) (originalImg.Width * resizeFactor);
                newHeight = (int) (originalImg.Height * resizeFactor);

            }
            
            // Resize the image                                                
            System.Drawing.Bitmap newImg = new System.Drawing.Bitmap(originalImg, newWidth, newHeight);
           

            // Now crop it
            int m;
            System.Drawing.Rectangle crop;            
            if (newImg.Width < newImg.Height) {
                m = (newImg.Height - newImg.Width) / 2;
                crop = new System.Drawing.Rectangle(0, m, newImg.Width, newImg.Width);
            } else {
                m = (newImg.Width - newImg.Height) / 2;
                crop = new System.Drawing.Rectangle(m, 0, newImg.Height, newImg.Height);
            }



            return newImg.Clone(crop, newImg.PixelFormat);
            
            

        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

        
        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {            
            SetChangeImageVisibility();
            if (MemberRow == null)
                Visibility = Visibility.Collapsed;
            else
                Visibility = Visibility.Visible;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e) {

            if (!Client.UserIsInRole(TeamRoles.FACTORY_OWNER))
                this.IsEnabled = false;

           

            if (!ShowAuthenticationGroupBox || IsClientManagement)
                authenticationGroupBox.Visibility = Visibility.Collapsed;

            if (IsReadingFromMSExchange && IsClientManagement) {
                this.IsEnabled = false;
                exchangeAlertBorder.Visibility = Visibility.Visible;
            }

            if (MemberRow == null)
                Visibility = Visibility.Collapsed;
            else
                Visibility = Visibility.Visible;


        }

        

        private void useWindowsAuthenticationCheckBox_Click(object sender, RoutedEventArgs e) {
            
            if (MemberRow == null)
                return;

            if (useWindowsAuthenticationCheckBox.IsChecked == true)
                MemberRow.SetAccessKeyNull();
            else
                MemberRow.AccessKey = Guid.NewGuid().ToString().ToLower();

        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            if (MemberRow == null)
                return;
            MemberRow.AccessKey = Guid.NewGuid().ToString().ToLower();
        }

    }
}
